#include "connection.h"

std::map<std::string, Connection*> Connection::login_map;

Connection::Connection (std::string ip) : peer_ip (ip)  {

	pthread_mutex_init (&input_mutex, 0);
	pthread_mutex_init (&output_mutex, 0);
	pthread_mutex_init (&login_map_mutex, 0);

	is_logged = false;
	is_versioned = false;

	running = true;

	accept_time = time (0);

	pthread_create (&thread_id, 0, Connection::Thread, this);

}

Connection::~Connection () {

	running = false;
	
	pthread_join (thread_id, 0);

	pthread_mutex_destroy (&login_map_mutex);
	pthread_mutex_destroy (&output_mutex);
	pthread_mutex_destroy (&input_mutex);

}

bool Connection::IsPendingOutput () {

	bool ret_val;
	pthread_mutex_lock (&output_mutex);
	ret_val = output_queue.size ();
	pthread_mutex_unlock (&output_mutex);
	return ret_val;

}

const std::list<MessageHeader*>& Connection::LockOutputQueue () {

	pthread_mutex_lock (&output_mutex);
	return output_queue;

}

void Connection::UnlockOutputQueue () {

	pthread_mutex_unlock (&output_mutex);

}

void Connection::InputMessage (MessageHeader* Msg) {

	pthread_mutex_lock (&input_mutex);
	MessageHeader* NewMsg = (MessageHeader*)(new char [Msg->Length]);
	if (NewMsg) {

		memcpy (NewMsg, Msg, Msg->Length);
		input_queue.push_back (NewMsg);
		last_activity = time (0);

	}
	pthread_mutex_unlock (&input_mutex);

}

void Connection::PostMessage (MessageHeader* Msg) {

	pthread_mutex_lock (&output_mutex);
	MessageHeader* NewMsg = (MessageHeader*)(new char [Msg->Length]);
	if (NewMsg) {

		memcpy (NewMsg, Msg, Msg->Length);
		output_queue.push_back (NewMsg);

	}
	pthread_mutex_unlock (&output_mutex);

}

std::string Connection::GetPeerIP () {

	return peer_ip;

}

void* Connection::Thread (void* Ptr) {

	Connection* This = (Connection*) Ptr;

	ReqVersion req_version;
	//request version

	while (This->running) {

		pthread_mutex_lock (&This->input_mutex);

		while (!This->input_queue.empty ()) {

			MessageHeader* Msg = This->input_queue.front ();
			This->input_queue.pop_front ();

			if (!This->is_versioned) {

				if (Msg->Type == RSP_VERSION) {

					

				}

			}

			delete Msg;

		}

		pthread_mutex_unlock (&This->input_mutex);

	}

	return 0;

}
	
